package com.xl.web;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.helpers.MessageFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created with 徐立.
 *
 * @author 徐立
 * @date 2022-07-23
 * @time 23:33
 * To change this template use File | Settings | File Templates.
 */
@RestController
@Slf4j
public class RootAction {
    @Autowired
    private Environment environment;

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @RequestMapping("/")
    public String index(HttpServletRequest request) {
        String property = environment.getProperty("local.server.port");
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();
        String collect = handlerMethods.keySet().stream().map(x -> x.getPatternsCondition()).map(Object::toString).map(s -> s.replaceAll("[\\[\\]]", "")).map(s -> {
            return "<a href=\"" + s + "\" target=\"_bank\" >" + s + "</a>";
        }).collect(Collectors.joining("<br/>"));
        List<String> headers = getHeaders(request);
        //获取客户端ip
        String remoteAddr = request.getRemoteAddr();
        return MessageFormatter.arrayFormat("这是小帅的个人网站 客户端ip:{} <br/>，请求头：<br/>{} <br/>端口号是:{},<br/>网址是：{}<br/>", new Object[]{remoteAddr,headers.stream().collect(Collectors.joining("<br/>")), property, collect}).getMessage();
    }

    /**
     * 获取请求头
     *
     * @param request
     * @return
     */
    private List<String> getHeaders(HttpServletRequest request) {
        List<String> headers = new ArrayList<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String header = headerNames.nextElement();
            headers.add("头：" + header + "：值：" + request.getHeader(header));
        }
        return headers;
    }
}
